package com.luzhikun.myshopping.controller;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "DownLoadServlet", value = "/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fname = request.getParameter("fname");
        System.out.println("fname"+"==="+fname);
        // 获取保存文件的绝对路径
        String realPath = request.getServletContext().getRealPath("/upload/");
        System.out.println("realPath"+"==="+realPath);
        // 获取到指定位置的文件
        File  file = new File(realPath,fname);
        // 指定下载的类型
        response.setContentType("image/jpeg");
        // 指定文件名的字符集
        String nameEncoding = new String(fname.getBytes("utf-8"),"iso-8859-1");
        // 设置以附件的形式下载 并且设置字符集
        response.setHeader("Content-disposition","attachment;filename="+nameEncoding);
        // 创建输入流和输出流
        FileInputStream inputStream = new  FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();

        int a = -1;
        while ((a=inputStream.read()) !=-1){
            outputStream.write(a);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
